<template>
	<view class="container">
		<view class="login-box">
			<view class="logo-section">
				<image class="logo" src="/static/logo.png"></image>
				<text class="app-name">沙扒湾旅游</text>
				<text class="app-slogan">探索美丽沙扒湾，畅游无限精彩</text>
			</view>
			
			<!-- 用户信件内容 -->
			<scroll-view 
				class="letter-container" 
				scroll-y 
				@scroll="handleScroll" 
				:scroll-top="scrollTop"
				:lower-threshold="100"
				@scrolltolower="handleScrollToBottom"
			>
				<view class="letter-content">
					<text class="letter-title">亲爱的用户：</text>
					<text class="letter-paragraph">欢迎来到沙扒湾旅游小程序！</text>
					<text class="letter-paragraph">沙扒湾位于广东省阳江市阳西县南部，是一个美丽的海滨旅游胜地。这里有细腻洁白的沙滩、清澈湛蓝的海水、壮观的日落景色以及丰富多样的海鲜美食。</text>
					<text class="letter-paragraph">通过我们的小程序，您可以：</text>
					<view class="letter-list">
						<text class="letter-list-item">• 了解沙扒湾最热门的景点和活动</text>
						<text class="letter-list-item">• 获取当地美食、住宿和交通的详细信息</text>
						<text class="letter-list-item">• 阅读其他游客分享的旅游攻略和体验</text>
						<text class="letter-list-item">• 收藏您感兴趣的内容，规划您的完美行程</text>
					</view>
					<text class="letter-paragraph">我们致力于为您提供便捷、全面的旅游信息服务，希望能够帮助您在沙扒湾度过一段难忘的时光。</text>
					<text class="letter-paragraph">登录后，您将获得个性化的推荐和更多功能。我们尊重您的隐私，仅收集必要的信息以提供更好的服务体验。</text>
					<text class="letter-paragraph">期待与您一起探索沙扒湾的美丽风光！</text>
					<text class="letter-signature">沙扒湾旅游团队</text>
					<text class="letter-date">2023年10月</text>
					<view class="scroll-indicator" :class="{'hidden': hasScrolledToBottom}">
						<text>请向下滑动阅读</text>
						<view class="arrow-down"></view>
					</view>
				</view>
			</scroll-view>
			
			<view class="login-section" :class="{'visible': hasScrolledToBottom}">
				<button 
					class="wechat-login-btn"
					open-type="getUserInfo"
					withCredentials="true"
					lang="zh_CN"
					@getuserinfo="handleGetUserInfo">
					<image class="wechat-icon" src="/static/logo.png"></image>
					<text class="login-text">微信一键登录</text>
				</button>
				
				<view class="agreement-section">
					<checkbox-group @change="handleAgreementChange">
						<label class="agreement-label">
							<checkbox :checked="isAgreed" color="#07C160" style="transform:scale(0.7)" />
							<text class="tip-text">我已阅读并同意</text>
							<text class="agreement-text" @tap.stop="showAgreement">《用户协议》和《隐私政策》</text>
						</label>
					</checkbox-group>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				redirectUrl: '/pages/my/index',
				lastLoginTime: 0,
				canIUse: wx.canIUse('button.open-type.getUserInfo'),
				isAgreed: false,
				hasScrolledToBottom: false,
				scrollTop: 0
			}
		},
		onLoad(options) {
			// 获取重定向地址
			if (options.redirect) {
				this.redirectUrl = decodeURIComponent(options.redirect);
			}
		},
		methods: {
			// 监听滚动
			handleScroll(e) {
				// 可以通过这个方法实时监控滚动位置
				console.log('滚动位置：', e.detail.scrollTop);
			},
			
			// 监听滚动到底部
			handleScrollToBottom() {
				console.log('已滚动到底部');
				this.hasScrolledToBottom = true;
			},
			
			// 协议勾选变化
			handleAgreementChange(e) {
				this.isAgreed = !!e.detail.value.length;
			},
			
			// 显示协议内容
			showAgreement() {
				// 防止冒泡触发checkbox状态变化
				wx.showModal({
					title: '用户协议与隐私政策',
					content: '感谢您使用沙扒湾旅游小程序。我们非常重视您的个人信息和隐私保护，请您仔细阅读并理解用户协议和隐私政策的全部内容。',
					confirmText: '我已阅读',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							this.isAgreed = true;
						}
					}
				});
			},
			
			// 通过open-type按钮获取到的用户信息
			handleGetUserInfo(e) {
				// 检查是否已勾选协议
				if (!this.isAgreed) {
					wx.showToast({
						title: '请先阅读并同意用户协议和隐私政策',
						icon: 'none'
					});
					return;
				}
				
				if (e.detail.userInfo) {
					// 用户点击了允许授权
					console.log('获取用户信息成功:', e.detail);
					this.loginWithUserInfo(e.detail);
				} else {
					// 用户拒绝授权，使用默认信息继续登录
					console.error('用户拒绝授权');
					this.loginWithDefault();
				}
			},
			
			// 使用获取到的用户信息登录
			async loginWithUserInfo(profileRes) {
				try {
					// 检查登录频率限制
					const now = Date.now();
					if (now - this.lastLoginTime < 2000) {
						wx.hideLoading();
						wx.showToast({
							title: '操作太频繁，请稍后再试',
							icon: 'none'
						});
						return;
					}
					this.lastLoginTime = now;
					
					// 显示加载提示
					wx.showLoading({
						title: '登录中...'
					});
					
					// 1. 微信登录获取code
					const loginRes = await new Promise((resolve, reject) => {
						wx.login({
							success: resolve,
							fail: reject
						});
					});
					
					console.log('微信登录成功，获取code:', loginRes.code);
					
					// 2. 发送请求到后端
					const res = await new Promise((resolve, reject) => {
						wx.request({
							url: this.$baseUrl + '/auth/wxlogin',
							method: 'POST',
							data: {
								code: loginRes.code,
								encryptedData: profileRes.encryptedData,
								iv: profileRes.iv
							},
							success: resolve,
							fail: reject
						});
					});
					
					wx.hideLoading();
					
					if (res.data.code === 200) {
						// 登录成功，保存token和用户信息
						wx.setStorageSync('token', res.data.data.token);
						wx.setStorageSync('userInfo', JSON.stringify(res.data.data.userInfo));
						
						// 提示登录成功
						wx.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 1500,
							success: () => {
								setTimeout(() => {
									if (this.redirectUrl.startsWith('/pages/my/')) {
										wx.switchTab({
											url: this.redirectUrl,
											fail: (err) => {
												console.error('跳转失败:', err);
												wx.redirectTo({
													url: this.redirectUrl
												});
											}
										});
									} else {
										wx.redirectTo({
											url: this.redirectUrl
										});
									}
								}, 1500);
							}
						});
					} else {
						throw new Error(res.data.message || '登录失败');
					}
				} catch (error) {
					console.error('登录失败:', error);
					wx.hideLoading();
					wx.showToast({
						title: error.message || '登录失败',
						icon: 'none'
					});
				}
			},
			
			// 用户拒绝授权时，使用默认信息登录
			async loginWithDefault() {
				// 检查是否已勾选协议
				if (!this.isAgreed) {
					wx.showToast({
						title: '请先阅读并同意用户协议和隐私政策',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 检查登录频率限制
					const now = Date.now();
					if (now - this.lastLoginTime < 2000) {
						wx.hideLoading();
						wx.showToast({
							title: '操作太频繁，请稍后再试',
							icon: 'none'
						});
						return;
					}
					this.lastLoginTime = now;
					
					// 显示加载提示
					wx.showLoading({
						title: '登录中...'
					});
					
					// 1. 微信登录获取code
					const loginRes = await new Promise((resolve, reject) => {
						wx.login({
							success: resolve,
							fail: reject
						});
					});
					
					console.log('微信登录成功，获取code:', loginRes.code);
					
					// 2. 发送请求到后端，使用空的加密数据
					const res = await new Promise((resolve, reject) => {
						wx.request({
							url: this.$baseUrl + '/auth/wxlogin',
							method: 'POST',
							data: {
								code: loginRes.code,
								encryptedData: '',
								iv: ''
							},
							success: resolve,
							fail: reject
						});
					});
					
					wx.hideLoading();
					
					if (res.data.code === 200) {
						// 登录成功，保存token和用户信息
						wx.setStorageSync('token', res.data.data.token);
						wx.setStorageSync('userInfo', JSON.stringify(res.data.data.userInfo));
						
						// 提示登录成功
						wx.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 1500,
							success: () => {
								setTimeout(() => {
									if (this.redirectUrl.startsWith('/pages/my/')) {
										wx.switchTab({
											url: this.redirectUrl,
											fail: (err) => {
												console.error('跳转失败:', err);
												wx.redirectTo({
													url: this.redirectUrl
												});
											}
										});
									} else {
										wx.redirectTo({
											url: this.redirectUrl
										});
									}
								}, 1500);
							}
						});
					} else {
						throw new Error(res.data.message || '登录失败');
					}
				} catch (error) {
					console.error('登录失败:', error);
					wx.hideLoading();
					wx.showToast({
						title: error.message || '登录失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #e6f7ff;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx;
	}
	
	.login-box {
		width: 100%;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.1);
		padding: 60rpx 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		max-height: 90vh;
	}
	
	.logo-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;
	}
	
	.logo {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 20rpx;
	}
	
	.app-name {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.app-slogan {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 信件样式 */
	.letter-container {
		width: 100%;
		max-height: 60vh;
		margin-bottom: 30rpx;
	}
	
	.letter-content {
		padding: 20rpx 10rpx;
		position: relative;
		min-height: 70vh; /* 确保内容足够长，可以滚动 */
	}
	
	.letter-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		display: block;
	}
	
	.letter-paragraph {
		font-size: 30rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 20rpx;
		display: block;
		text-align: justify;
	}
	
	.letter-list {
		margin: 20rpx 0 30rpx 20rpx;
	}
	
	.letter-list-item {
		font-size: 30rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.letter-signature {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-top: 40rpx;
		display: block;
		text-align: right;
	}
	
	.letter-date {
		font-size: 28rpx;
		color: #999;
		display: block;
		text-align: right;
		margin-bottom: 60rpx;
	}
	
	.scroll-indicator {
		position: absolute;
		bottom: 10rpx;
		left: 0;
		right: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #999;
		font-size: 24rpx;
		opacity: 0.7;
		animation: bounce 2s infinite;
		transition: opacity 0.3s;
	}
	
	.scroll-indicator.hidden {
		opacity: 0;
	}
	
	.arrow-down {
		width: 20rpx;
		height: 20rpx;
		border-right: 3rpx solid #999;
		border-bottom: 3rpx solid #999;
		transform: rotate(45deg);
		margin-top: 10rpx;
	}
	
	@keyframes bounce {
		0%, 20%, 50%, 80%, 100% {
			transform: translateY(0);
		}
		40% {
			transform: translateY(-10rpx);
		}
		60% {
			transform: translateY(-5rpx);
		}
	}
	
	.login-section {
		width: 100%;
		opacity: 0;
		transition: opacity 0.5s ease;
		pointer-events: none;
	}
	
	.login-section.visible {
		opacity: 1;
		pointer-events: auto;
	}
	
	.wechat-login-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #07C160;
		color: #FFFFFF;
		height: 90rpx;
		border-radius: 45rpx;
		margin-bottom: 30rpx;
		border: none;
		padding: 0;
	}
	
	.wechat-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}
	
	.login-text {
		font-size: 32rpx;
		color: #FFFFFF;
	}
	
	.agreement-section {
		display: flex;
		justify-content: center;
		margin-top: 10rpx;
	}
	
	.agreement-label {
		display: flex;
		align-items: center;
	}
	
	.tip-text {
		font-size: 24rpx;
		color: #999;
	}
	
	.agreement-text {
		font-size: 24rpx;
		color: #1296db;
		margin-left: 6rpx;
	}
</style> 